import request from "../../utils/request"
Page({
  data: {
    list: [],
    total: 0
  },
  checkedChange(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const copy = Object.assign([], this.data.list);
    copy[index].checked = !copy[index].checked;
    this.setData({
      list: copy
    })
    this.totalFn();
  },
  totalFn() {
    let total = 0;
    this.data.list.forEach(item => {
      if (item.checked) {
        total += (item.quantity * item.productSku.price)
      }
    })
    this.setData({
      total
    })
  },
  onSubmit() {
    const list = this.data.list.filter(item => item.checked);
    if (list.length) {
      wx.setStorageSync('addOrder', list);
      wx.navigateTo({
        url: '/pages/createOrder/createOrder',
      })
    } else {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
    }
  },
  async getList() {
    const userId = wx.getStorageSync('userInfo').id;
    const res = await request.get(`/cart/page?userId=${userId}`);
    console.log(res, "购物车");
    res.data.data.forEach(item => {
      item.checked = false;
    })
    this.setData({
      list: res.data.data
    })
  },
  onShow() {
    if (wx.getStorageSync('userInfo')) {
      this.getList();
    }
  }
})